package com.project.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.project.exception.ServiceException;
import com.project.result.ResultCode;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
@SuppressWarnings("all")
/**
 * @ProjectName:
 * @Package:
 * @ClassName:
 * @Author: ZhaoLongShi
 * @CreateDate:
 */
@Component
public class Upload {
    public static final String IMG_PREFIX_FILE = "IMG_";
    public static final String DATE_FORMAT = "yyyyMMddHHmmss";
    public static final String BUCKET_NAME_IMAGE = "images";


    @Resource
    private OSS oss;
    @Resource
    private OSSConfigProperties properties;

    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    public String uploadImg(MultipartFile multipartFile) {
        //获取原文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //拼接新名字防止重名
        String newFileName =  getNewFileName(originalFilename);
        //相当于文件的全路径名
        String key = BUCKET_NAME_IMAGE + "/" + DateUtils.formatDate(new Date(),
                "yyyy-MM-dd HH:mm:ss") + "/" + newFileName;
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(getcontentType(originalFilename.substring(originalFilename.lastIndexOf("."))));
            //上传文件到阿里云服务器
            ByteArrayInputStream inputStream = new ByteArrayInputStream(multipartFile.getBytes());
            PutObjectResult result = oss.putObject(properties.getBucketName(), key, inputStream,objectMetadata);
            if (!ObjectUtils.isEmpty(result.getETag())) {
                //如果上传文件返回结果不为空，则获取并返回文件路径
                return getUrl(properties.getBucketName(), key);
            } else {
                throw new ServiceException(ResultCode.FILE_UPLOAD_ERROR);
            }
        } catch (IOException e) {
            throw new ServiceException(ResultCode.SYSTEM_INNER_ERROR);
        }
    }

    /**
     * 重命名文件
     *
     * @param originalFileName
     * @return
     */
    private static String getNewFileName(String originalFileName) {
        //获取原文件后缀名
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        //进行文件名拼接并返回
        return String.format("%s%s%s", IMG_PREFIX_FILE,
                DateUtils.formatDate(new Date(), DATE_FORMAT),suffix);
    }

    /**
     * 获取上传成功后的访问地址
     *
     * @param bucketName
     * @param key
     * @return
     */
    private String getUrl(String bucketName, String key) {
        //存储有效时间
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        return oss.generatePresignedUrl(bucketName, key, expiration).toString();
    }

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}
